import { useShios } from 'shios';
import { store } from '@/store';
import { ElMessage } from 'element-plus';
import router from '@/route';

export const shios = useShios(import.meta.env.VITE_API_BASE_URL);
shios.token = store.token.state.accessToken;
shios.isCache = false;
shios.failureHandler = async function (res, pathname, init) {
  console.log(res);
  if (res.status == 401) {
    if (res.headers?.['expires']) {
      console.error(res.headers?.['expires']);
      const controllerName = res.url.split(/[/?]/, 1)[0];
      caches.delete(controllerName);
      const response = await shios.post<Token>('login/RefreshAuthToken', {
        data: store.token.state,
      });
      if (response.ok) {
        store.token.update(response.data);
        this.token = response.data.accessToken;
        return shios.requst(pathname, init);
      } else {
        ElMessage.error('登录超时');
      }
    }
    router.push('/login');
  } else if (res.status == 404) {
    router.replace('/NotFound');
  } else if (res.error) {
    if (typeof res.error == 'string') {
      ElMessage.error({ message: res.error, grouping: true });
    } else if (res.error.errors) {
      for (const key in res.error.errors) {
        if (key in res.error.errors) {
          const errors = res.error.errors[key];
          for (const err of errors) {
            ElMessage.error({ message: err, grouping: true });
          }
        }
      }
    } else if (res.error.title) {
      ElMessage.error({ message: res.error.title, grouping: true });
    }
  } else if (res.statusText) {
    ElMessage.error({ message: res.statusText, grouping: true });
  } else {
    ElMessage.error({ message: res.status?.toString(), grouping: true });
  }
  //throw new Error(res.url);
};
